<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>键盘事件</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #divBox {
            width: 30px;
            height: 30px;
            background: #f06060;
            text-align: center;
            line-height: 30px;
            font-size: 25px;
            margin: 100px 0 0 100px;
        }

        #divNum {
            width: 600px;
            height: 20px;
            border: 1px solid #f06060;
            margin: 400px 0 0 200px;
            text-align: center;
        }
    </style>
    <script src="../../jquery-js/jquery.js"></script>
    <script>
        $(document).keydown(function (ev) {
            let $option = ev.which;  //获取当前键盘的对应码值 keyCode
            let $item = $('#divBox'); //获取操作元素
            let $left = $item.offset().left; // 获取元素到文档左侧的距离
            let $top = $item.offset().top; // 获取元素到文档上面的距离
            switch ($option) {
                case 37:
                    // 左
                    $item.offset({
                        left: $left - 1, top: $top
                    });
                    break;
                case 38:
                    // 上
                    $item.offset({
                        left: $left, top: $top - 1
                    });
                    break;
                case 39:
                    // 右
                    $item.offset({
                        left: $left + 1, top: $top
                    });
                    break;
                case 40:
                    // 下
                    $item.offset({
                        left: $left, top: $top + 1
                    });
                    break;
            }

            $('#divNum').text('左：' + ($left - 1) + 'px     ' + '上：' + ($top - 1) + 'px     ' +
                '右：' + ($left + 1) + 'px     ' + '下：' + ($top + 1) + 'px');
        });
    </script>
</head>
<body>
<div id="divBox">
    *
</div>
<div id="divNum"></div>
</body>
</html>